package com.df.hitime.controller;

import com.df.hitime.base.BaseController;
import com.df.hitime.model.UserRole;
import com.df.hitime.service.TestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Optional;

/**
 * @author liurx
 * @date 2018/11/20 9:42
 */
@RestController
@RequestMapping("/index")
public class IndexController extends BaseController {
    @Autowired
    TestService testService;

    @RequestMapping("/list")
    public Object list(String code,String state) {
        String sessionId=httpServletRequest.getSession().getId();
        System.out.println("sessionId:"+sessionId);
        System.out.println("code:"+code);
        System.out.println("state:"+state);
        List<UserRole> list = (List<UserRole>) testService.findAll();
        return success(list);
    }

    @RequestMapping("/findOne")
    public Object findOne(Integer id) {
        Optional<UserRole> role = testService.findById(id);
        return success(role.get());
    }

    @RequestMapping("/save")
    public Object save(String name) {

        UserRole userRole = new UserRole();
        if (StringUtils.isEmpty(name)) {
            name = "123";
        }
        userRole.setName(name);
        testService.save(userRole);
        return success(userRole);
    }

    @RequestMapping("/del")
    public Object del(Integer id) {
        testService.deleteById(id);
        return success();
    }

    @RequestMapping("/update")
    public Object udpate(Integer id, String name) {
        Optional<UserRole> optional = testService.findById(id);
        if (!optional.isPresent()) {
            return error("不存在");
        }
        UserRole role = optional.get();
        role.setName(name);
        testService.save(role);
        return success(role);
    }

    @RequestMapping("/error")
    public Object error() {
        int i = 1 / 0;
        return error("失败");
    }
}
